/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : my_home.js                            
*  Description  : 마이홈
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-06-25  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	// 예약현황
	function clsReserveList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsReserveList.prototype = {
		_init: function(){
			var $layer = $("div#container table.list01");
			var $img1 = $layer.find("img[alt='보증 결제하기']:first, img[alt='예약취소']:first");
			$layer.find("tbody tr:first td:eq(8)").empty().append($img1);
			
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("tbody tr:first").clone(true)
			}
			
			this.setList([]);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			var objS = {
				"W": "예약 대기"
				, "P": "가예약(결제대기)"
				, "G": "예약 완료"
				, "A": "예약 완료"
				, "PC": "가예약취소"
				, "GC": "예약취소"
			}
			
			var myInfo = _gf.getMyInfoData();
			
			$layer.find("tbody").empty();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("tbody").append($element.clone(true));
			}
			
			$layer.find("tbody tr").each(function(n){
				var d = thisClass.listData[n];
				
				$(this).find("td.day").html(d["예약날짜"]);
				$(this).find("td.time").html(d["시간"]);
				$(this).find("td:eq(2)").html(_gf.getAreaText(d["지역코드"]));
				$(this).find("td:eq(3)").html(d["골프장명"] + " " + d["코스명"]);
				$(this).find("td.td_price p:eq(0)").html(_util.number_format(d["그린피"]));
				$(this).find("td.td_price p:eq(1)").html(_util.number_format(d["원가"]));
				$(this).find("td.name").html(myInfo["닉네임"]);
				$(this).find("td.re_c").html(objS[d["예약상태코드"]]);
				
				var bName = "";
				switch(d["예약상태코드"]){
					case "P":
						bName = "보증 결제하기";
					case "G":
					case "A":
						if(bName) bName += ",";
						bName += "예약취소";
						break;
				}
				
				$(this).find("td:eq(8) img").each(function(){
					if(bName.indexOf($(this).attr("alt")) == -1) $(this).hide();
					else $(this).show();
				});
				
				$(this).find("td.sms img").hide();
				if(d["예약상태코드"] == "G") $(this).find("td.sms img").show();
			});
		}
		, spinStart: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("tbody").hide();
			if($layer.next("div#tmpSpin").length == 0){
				$layer.after("<div id='tmpSpin' style='position:relative; width:900px; height:100px;' />");
			}
			$layer.next("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("tbody").show();
			$layer.next("div#tmpSpin").hide().spin(false);
		}
		, getKey: function(n){
			return this.listData[n]["예약코드"];
		}
		, getAreaKey: function(n){
			return this.listData[n]["지역코드"];
		}
		, getGolfKey: function(n){
			return this.listData[n]["골프장코드"];
		}
		, getCourseKey: function(n){
			return this.listData[n]["코스코드"];
		}
		, getReserveStat: function(n){
			return this.listData[n]["예약상태코드"];
		}
	}
	
	
	// 서버통신
	function clsComm()
	{
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			
		}
		// 예약현황
		, getReserveList: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "getMyReservList";
			var options = {
				
			}
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
				, "listcount": arg["페이지당수"]
				, "currpageno": arg["페이지"]
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "전체수":  ret["msp"]["contents"]["@totalcount"]
					, "결과값": []
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						var reserv_date = _util.nvl(obj["reserv__date"])+"";
						var reserv_time = _util.nvl(obj["reserv__time"])+"";
						
						res["결과값"].push({
							"예약코드": _util.nvl(obj["reserv__seq"])
							, "예약날짜": reserv_date.substrEx(0, 4) + "." + reserv_date.substrEx(4, 2) + "." + reserv_date.substrEx(6, 2)
							, "시간": reserv_time.substrEx(0, 2) + ":" + reserv_time.substrEx(2, 2)
							, "지역코드": _util.nvl(obj["region"])
							, "골프장코드": _util.nvl(obj["golfclub__id"])
							, "코스코드": _util.nvl(obj["course__info__id1"])
							, "골프장명": _util.nvl(obj["golfclub__name"])
							, "코스명": _util.nvl(obj["course__info__name1"])
							, "그린피": _util.nvl(obj["greenfee"], _util.nvl(obj["price"], 0))
							, "원가": _util.nvl(obj["price"], 0)
							, "예약상태코드": _util.nvl(obj["reserv__status"])
						});
					}
				}
				
				document.objControl.finishReserveList(res);
			});
		}
		// 가예약취소
		, reserveCancel: function(arg){
			var thisClass = this;
			
			arg = arg || {}
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "reservCancel";
			var options = {
				"reserv_seq": arg["예약코드"]
				, "reserv_status": arg["예약상태"]
			}
			_gf.ajax({
				"sid": "RS001"
				, "servicename": serviceName
			}, options,  function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objReserveList = null;
		this.objReservePaging = null;
		
		this._permitStart = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objReserveList = new clsReserveList();
			this.objReservePaging = _gf.makePaging($("div#idReservePaging"), 10, 10);
			
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
			
			$("div#container section#my_home").append("<div id='idReservePaging' />");
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			$.ajax({
				url: _ROOT + "/js/mypage_common.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				for(var k in thisClass._beforeStart){
					if(!thisClass._beforeStart[k]) return false;
				}
				
				return (_gf.getMyInfoData());
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			this.objReserveList.$getLayer().on("click", "td.sms img", function(){
				var e = arguments[0] || event;
				
				e.cancelBubble = true;
				
				var alt = $(this).attr("alt");
				var n = thisClass.objReserveList.$getLayer().find("td.sms img[alt='" + alt + "']").index($(this));
				var k = thisClass.objReserveList.getKey(n);
				
				switch(alt){
					case "이메일 알림":
						thisClass.goEmailAlimPage(k);
						break;
					case "SMS 알림":
						thisClass.goSmsAlimPage(k);
						break;
				}
			});
			
			// 실시간 예약
			this.objReserveList.$getLayer().on("click", "tbody tr", function(){
				var e = arguments[0] || event;
				var o = e.target;
				
				if(o.tagName.toUpperCase() == "IMG" && ($(o).attr("alt") == "이메일 알림" || $(o).attr("alt") == "SMS 알림")) return;
				
				var n = thisClass.objReserveList.$getLayer().find("tbody tr").index($(this));
				var k = thisClass.objReserveList.getKey(n);
				var a = thisClass.objReserveList.getAreaKey(n);
				var g = thisClass.objReserveList.getGolfKey(n);
				var c = thisClass.objReserveList.getCourseKey(n);
				
				thisClass.goReserveViewPage(k, a, g, c);
			});
			
			// 페이지이동
			$(this.objReservePaging).bind("evtPageClick", function(){
				thisClass.getReserveList();
			});
			
			$("div#container section#my_home").on("click", "img[alt='부킹정보 보기']", function(){
				var alt = $(this).attr("alt");
				
				switch(alt){
					case "부킹정보 보기":
						thisClass.goBookingList();
						break;
				}
			});
			
			// 예약현황
//			this.objReserveList.$getLayer().on("click", "img[alt='예약취소']", function(){
//				var alt = $(this).attr("alt");
//				
//				switch(alt){
//					case "예약취소":
//						var n = thisClass.objReserveList.$getLayer().find("img[alt='예약취소']").index($(this));
//						var k = thisClass.objReserveList.getKey(n);
//						var s = thisClass.objReserveList.getReserveStat(n);
//						
//						thisClass.reserveCancel(k, s);
//						break;
//				}
//			});
		}
		, _start: function(){
			// 예약현황
			this.objReservePaging.setPage(1);
			this.getReserveList();
		}
		// 예약현황 완료
		, finishReserveList: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objReserveList.spinEnd();
			
			this.objReservePaging.setTotalCount(ret["전체수"]);
			this.objReservePaging.display();
			this.objReserveList.setList(ret["결과값"]);
		}
		// 예약취소 완료
		, finishReserveCancel: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			_gf.spinEnd();
			
			this.objReserveList.spinStart();
			this.getReserveList();
		}
		// 예약현황
		, getReserveList: function(){
			this.objReserveList.spinStart();
			this.objComm.getReserveList({
				"페이지당수": this.objReservePaging.getCountPerPage()
				, "페이지": this.objReservePaging.getPage()
			});
		}
		// 예약취소
		, reserveCancel: function(k, s){
			var thisClass = this;
			
			var conf = "예약을 취소하시겠습니까?\n[확인]을 누르시면 예약이 취소됩니다.";
			if(s == "P") conf = "가" + conf;
			
			if(!confirm(conf)) return;
			
			_gf.spinStart("sending...");
			this.objComm.reserveCancel({
				"예약코드": k
				, "예약상태": s
				, "콜백": function(ret){
					thisClass.finishReserveCancel(ret);
				}
			});
		}
		// 부킹정보 페이지
		, goBookingList: function(){
			var szLink = _ROOT + "/mypage/my_booking.html";
			document.location.href = szLink;
		}
		// 예약 상세 이동
		, goReserveViewPage: function(seq, area, golf, course){
			var param = {
				"q_reserve": seq
				, "q_area": area
				, "q_golf": golf
				, "q_course": course
			}
			
			
			var szLink = _ROOT + "/booking/reserve_view.html" + _util.object2paramString(param);
			$("body").append("<a href='" + szLink + "' id='idPermissionLink' target='_blank'></a>");
			$("a:last").get(0).click();
			$("a:last").remove();
		}
		// 이메일 알림 이동
		, goEmailAlimPage: function(q_reserve){
			var szLink = _ROOT + "/popup/pop_email.html?q_reserve=" + q_reserve;
			var winEmailAlim = window.open(szLink, "winEmailAlim", "width=1000, height=600, scrollbars=0");
			if(winEmailAlim) winEmailAlim.focus();
		}
		// sms 발송 이동
		, goSmsAlimPage: function(q_reserve){
			var szLink = _ROOT + "/popup/pop_sms.html?q_reserve=" + q_reserve;
			var winSms = window.open(szLink, "winSms", "width=600, height=500, scrollbars=0");
			if(winSms) winSms.focus();
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});
